<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <meta name="description" content="">
    <meta name="author" content="">
    <!-- <link rel="icon" href="favicon.ico"> -->

    <title>AMC System - Merchant Side</title>

    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <link href="css/ie10-viewport-bug-workaround.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="css/dashboard.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
    <script src="js/ie-emulation-modes-warning.js"></script>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body>

    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
					<span class="sr-only">Toggle navigation</span> <span
						class="icon-bar"></span> <span class="icon-bar"></span> <span
						class="icon-bar"></span>
				</button>
                <a class="navbar-brand" href="#">AMC System - Merchant Side</a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
                <!-- <ul class="nav navbar-nav navbar-right">
					<li><a href="#"></a></li>
					<li><a href="#"></a></li>
					<li><a href="#"></a></li>
					<li><a href="#"></a></li>
				</ul> -->
                <form class="navbar-form navbar-right">
                    <input type="text" class="form-control" placeholder="Search...">
                </form>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-3 col-md-2 sidebar">
                <ul class="nav nav-sidebar">
                    <li class="active"><a href="#">商户信息<span class="sr-only">(current)</span></a></li>
                    <li><a href="#">商户名：</a></li>
                    <li><a href="#" id="merchantName"></a></li>
                    <li><a href="#">商户照片</a></li>
                    <li><a href="#" id="merchantPic"></a></li>
                    <li><a href="#"><button type="button" class="btn btn-primary" aria-pressed="false" autocomplete="off" id="logoutBtn">退出系统</button></a></li>
                </ul>
            </div>
            <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
                <h1 class="sub-header">菜品管理系统</h1>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <caption>菜品信息</caption>
                        <thead>
                            <tr>
                                <th>菜品ID</th>
                                <th>菜品名称</th>
                                <th>菜品价格</th>
                                <th>菜品图片</th>
                                <th>菜品类型</th>
                                <th>更新菜品</th>
                                <th>删除菜品</th>
                            </tr>
                        </thead>
                        <tbody id="foodsBody">

                        </tbody>
                    </table>
                </div>
                <button type="button" class="btn btn-primary" aria-pressed="false" autocomplete="off" data-toggle="modal" data-target="#addModal">新增菜品</button>
            </div>
        </div>
    </div>

    <!-- 模态框 -->
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
                    <h4 class="modal-title" id="myModalLabel">新增菜品</h4>
                </div>
                <!-- modal body -->
                <div class="modal-body">
                    <!-- form -->
                    <div class="form-group" id="addFoodNameForm">
                        <label for="exampleInputEmail1 ">菜品名称</label> <input type="text" class="form-control" id="addFoodName" placeholder="菜品名称">
                        <p class="help-block" id="addFoodNameValidateMessage"></p>
                    </div>
                    <div class="form-group">
                        <label for="exampleInputPassword1">菜品价格</label> <input type="text" class="form-control" id="addFoodPrice" placeholder="菜品价格">
                    </div>
                    <div class="form-group">
                        <label for="exampleInputFile">菜品类型</label> <select class="form-control" id="addFoodTypes">
                            <option value="1">快餐</option>
                            <option value="2">当地美食</option>
                            <option value="3">西式</option>
                            <option value="4">异国美食</option>
                            <option value="5">中餐</option>
                            <option value="6">烧烤</option>
                            <option value="7">甜食</option>
                            <option value="8">水果</option>
                            <option value="9">饮料</option>
						</select>
                    </div>
                    <div class="form-group">
                        <label for="exampleInputFile">菜品图片</label> <input type="file" name="foodPic" id="addFoodPic">
                        <input type="text" name="realpath" id="realpath" hidden/>
                        <button id="uploadBtn">上传图片</button>
                        <p class="help-block">上传图片请不要超过2M.</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="addOnclick()">Save
						changes</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 模态框 -->
    <div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
                    <h4 class="modal-title" id="myModalLabel">更新菜品</h4>
                </div>
                <!-- modal body -->
                <div class="modal-body">
                    <!-- form -->
                    <div class="form-group">
                        <label for="exampleInputEmail1 ">菜品ID</label> <input type="text" readonly="readonly" class="form-control" id="updateFoodId">
                    </div>
                    <div class="form-group">
                        <label for="exampleInputEmail1 ">菜品名称</label> <input type="text" class="form-control" id="updateFoodName" placeholder="菜品名称">
                    </div>
                    <div class="form-group">
                        <label for="exampleInputPassword1">菜品价格</label> <input type="text" class="form-control" id="updateFoodPrice" placeholder="菜品价格">
                    </div>
                    <div class="form-group">
                        <label for="exampleInputFile">菜品类型</label>
                        <select class="form-control" id="updateFoodTypes">
                            <option value="1">快餐</option>
                            <option value="2">当地美食</option>
                            <option value="3">西式</option>
                            <option value="4">异国美食</option>
                            <option value="5">中餐</option>
                            <option value="6">烧烤</option>
                            <option value="7">甜食</option>
                            <option value="8">水果</option>
                            <option value="9">饮料</option>
						</select>
                    </div>
                    <div class="form-group">
                        <label for="exampleInputFile">菜品图片</label> <input type="file" id="updateFoodPic">
                        <input type="text" name="updateRealpath" id="updateRealpath" hidden/>
                        <button id="updateUploadBtn">上传图片</button>
                        <p class="help-block">上传图片请不要超过2M.</p>
                    </div>
                    <div class="form-group">
                        <input type="text" name="uploadMerchantId" id="updateMerchantId" hidden/>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="updateModelOnclick()">Save
						changes</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="js/jquery.min.js"></script>
    <script>
        window.jQuery ||
            document
            .write('<script src="js/jquery.min.js"><\/script>')

    </script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Just to make our placeholder images work. Don't actually copy the next line! -->
    <script src="js/holder.min.js"></script>
    <script src="js/jquery.uploadify.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="js/ie10-viewport-bug-workaround.js"></script>
    <!-- user-defined js -->
    <script>
        var foodType = ["其他","快餐", "当地美食", "西式", "异国美食", "中餐", "烧烤", "甜食", "水果", "饮料", "其他"];

        function getContent() {
            $.ajax({
                // url: "http://localhost:8080/ContentServletMock",
                url: "http://localhost:8080/AjaxQueryFoodServlet",
                method: "GET",
                success: function(
                    item) {
                    var protocal = JSON.parse(item);
                    var status = protocal.status;
                    if (status == "success") {
                        var foods = protocal.data;
                        renderTable(foods);
                    }
                }
            });
        }

        function renderTable(foods) {
            var foodsBody = $("#foodsBody");
            foodsBody.empty();
            foods.forEach(function(item, index, array) {
                var foodId = item.foodId;
                var foodName = item.foodName;
                var foodPrice = item.foodPrice;
                var foodPic = item.foodPic;
                var foodTypeId = item.foodFoodTypeId;
                var merchantId = item.merchantId;

                var tr = document.createElement("tr");
                tr.setAttribute("id", foodId);
                tr.innerHTML += "<td>" + foodId + "</td>";
                tr.innerHTML += "<td>" + foodName + "</td>";
                tr.innerHTML += "<td>" + foodPrice + "</td>";
                tr.innerHTML += "<td><img src='" + foodPic + "' alt='图片无法显示' class='img-thumbnail' width=200px height=150px></td>";
                tr.innerHTML += "<td>" + foodType[foodTypeId] + "</td>";
                tr.innerHTML += `<td><button type='button' value='${foodId}' onclick='updateOnclick(this)' class='btn btn-primary' aria-pressed='false' autocomplete='off' data-toggle="modal" data-target="#updateModal">更新菜品</button></td>`;
                tr.innerHTML += `<td><button type='button' value='${foodId}' onclick='deleleOnclick(this)' class='btn btn-primary' aria-pressed='false' autocomplete='off'>删除菜品</button></td>`;
                foodsBody.append(tr);
            });
        }

        function addOnclick() {
            var foodName = $("#addFoodName").val();
            var foodPrice = $("#addFoodPrice").val();
            var foodType = $("#addFoodTypes").val();
            var foodPic = $("#realpath").val();

            $.ajax({
                url: "http://localhost:8080/AjaxAddFoodServlet?name=" + foodName + "&price=" + foodPrice + "&foodtype=" + foodType + "&foodPic=" + foodPic,
                method: "POST"
            });
            getContent();
        }

        function updateOnclick(k) {
            var foodId = k.value;
            $.ajax({
                url: "http://localhost:8080/AjaxUpdateFoodsContentServlet?foodId=" + foodId,
                method: "POST",
                success: function(item) {
                    var protocal = JSON.parse(item);
                    var status = protocal.status;
                    if (status == "success") {
                        var food = protocal.data;
                        $("#updateFoodId").val(food.foodId);
                        $("#updateFoodName").val(food.foodName);
                        $("#updateFoodPrice").val(food.foodPrice);
                        $("#updateRealpath").val(food.foodPic);
                        $("#updateMerchantId").val(food.merchantId);
                    }
                }
            });
        }

        function updateModelOnclick() {
            var foodId = $("#updateFoodId").val();
            var foodName = $("#updateFoodName").val();
            var foodPrice = $("#updateFoodPrice").val();
            var foodType = $("#updateFoodTypes").val();
            var foodPic = $("#updateRealpath").val();
            var merchantId = $("#updateMerchantId").val();

            //  + foodName + foodPrice + foodType + foodPic + merchantId;
            $.ajax({
                url: "http://localhost:8080/AjaxUpdateFoodServlet?id=" + foodId + "&name=" + foodName + "&price=" + foodPrice + "&foodtype=" + foodType + "&foodPic=" + foodPic + "&merchantId=" + merchantId,
                method: "POST",
                success: function(item) {
                    // var protocal = JSON.parse(item);
                    // var status = protocal.status;
                    // if (status == "error") {
                    //   alert(protocal.msg);
                    // }
                }
            });
            getContent();
        }

        function deleleOnclick(item) {
            $.ajax({
                url: "http://localhost:8080/AjaxDeleteFoodServlet?foodId=" + item.value,
                method: "GET"
            });
            getContent();
        }

        (function() {
            $(document).ready(function() {
                $.ajax({
                    url: "http://localhost:8080/AjaxQueryMerchantServlet",
                    method: "GET",
                    success: function(item) {
                        var protocal = JSON.parse(item);
                        //var status = protocal.status;
                        //if (status == "success") {
                        //    var merchant = protocal.data;
                        //    renderSidebar(merchant);
                        //}
                        renderSidebar(protocal);
                    }
                });
                getContent();
            });

            function renderSidebar(merchant) {
                var merchantName = merchant.merchantName;
                var merchantPic = merchant.merchantPic;

                $("#merchantName").html(merchantName);
                $("#merchantPic").html("<img src='" + merchantPic + "' alt='图片无法显示' class='img-thumbnail' width=280px height=175px>");
            }

            $("#logoutBtn").on("click", function() {
                $.ajax({
                    url: "http://localhost:8080/LogoutServlet",
                    type: "GET"
                });
                window.location.href = "http://localhost:8080";
            });

            $("#addFoodName").on("change", function() {
                var value = $("#addFoodName").val();
                var form = $("#addFoodNameForm");
                var message = $("#addFoodNameValidateMessage");

                if (value == "") {
                    form.removeClass("has-success");
                    form.removeClass("has-error");
                    message.html("");
                } else if (value.length > 10) {
                    form.removeClass("has-success");
                    form.addClass("has-error");
                    message.html("长度超过限制");
                } else {
                    form.removeClass("has-error");
                    form.addClass("has-success");
                    message.html("");
                }
            });

            window.setTimeout(poll, 3000);

            function poll() {
                console.log("poll");
                $.ajax({
                    url: "http://localhost:8080/AjaxMerchantStatusServlet",
                    method: "GET",
                    success: function(item) {
                        var protocal = JSON.parse(item);
                        var status = protocal.status;
                        if (status == "success") {
                            window.setTimeout(poll, 10000);
                        } else if (status == "error") {
                            alert(protocal.msg);
                            logout();
                        }
                    }
                });
            }

            function logout() {
                $.ajax({
                    url: "http://localhost:8080/LogoutServlet",
                    type: "GET"
                });
                window.location.href = "http://localhost:8080";
            }

            $("#addFoodPic").uploadify({
                'height': 27,
                'width': 80,
                'buttonText': '选择图片',
                'swf': 'css/uploadify.swf',
                'uploader': 'http://localhost:8080/AsyncUploadTestServlet',
                'queueID': 'fileQueue',
                'auto': false,
                'multi': true,
                'removeCompleted': false,
                'cancelImg': 'uploadify-cancel.png',
                'fileTypeExts': '*.jpg;*.jpge;*.gif;*.png',
                'fileSizeLimit': '2MB',
                'fileObjName': 'foodPic',
                'onUploadSuccess': function(file, data, response) {
                    $('#' + file.id).find('.data').html('');
                    $("#upload_org_code_name").val(data);
                    // var img = $("<img></img>");

                    // img.attr("src", "PicServlet?picName=" + data);
                    // img.appendTo($("#imgContainer"));
                    // alert("上传成功" + data);
                    var jsonObj = JSON.parse(data);
                    var status = jsonObj["status"];
                    if (status == "success") {
                        $("#realpath").val(jsonObj["path"]);
                        alert("文件上传成功");
                    } else {
                        alert("文件上传失败");
                    }
                },
                //加上此句会重写onSelectError方法【需要重写的事件】
                'overrideEvents': ['onSelectError', 'onDialogClose'],
                //返回一个错误，选择文件的时候触发
                'onSelectError': function(file, errorCode, errorMsg) {
                    switch (errorCode) {
                        case -110:
                            alert("文件 [" +
                                file.name +
                                "] 大小超出系统限制的" +
                                jQuery('#upload_org_code').uploadify(
                                    'settings', 'fileSizeLimit') +
                                "大小！");
                            break;
                        case -120:
                            alert("文件 [" + file.name + "] 大小异常！");
                            break;
                        case -130:
                            alert("文件 [" + file.name + "] 类型不正确！");
                            break;
                    }
                },
            });

            $("#uploadBtn").click(function() {
                $("#addFoodPic").uploadify("upload", "*");
            });

            // update
            $("#updateFoodPic").uploadify({
                'height': 27,
                'width': 80,
                'buttonText': '选择图片',
                'swf': 'css/uploadify.swf',
                'uploader': 'http://localhost:8080/AsyncUploadTestServlet',
                'queueID': 'fileQueue',
                'auto': false,
                'multi': true,
                'removeCompleted': false,
                'cancelImg': 'uploadify-cancel.png',
                'fileTypeExts': '*.jpg;*.jpge;*.gif;*.png',
                'fileSizeLimit': '2MB',
                'fileObjName': 'foodPic',
                'onUploadSuccess': function(file, data, response) {
                    $('#' + file.id).find('.data').html('');
                    $("#upload_org_code_name").val(data);

                    var jsonObj = JSON.parse(data);
                    var status = jsonObj["status"];
                    if (status == "success") {
                        $("#updateRealpath").val(jsonObj["path"]);
                        alert("文件上传成功");
                    } else {
                        alert("文件上传失败");
                    }
                },
                //加上此句会重写onSelectError方法【需要重写的事件】
                'overrideEvents': ['onSelectError', 'onDialogClose'],
                //返回一个错误，选择文件的时候触发
                'onSelectError': function(file, errorCode, errorMsg) {
                    switch (errorCode) {
                        case -110:
                            alert("文件 [" +
                                file.name +
                                "] 大小超出系统限制的" +
                                jQuery('#upload_org_code').uploadify(
                                    'settings', 'fileSizeLimit') +
                                "大小！");
                            break;
                        case -120:
                            alert("文件 [" + file.name + "] 大小异常！");
                            break;
                        case -130:
                            alert("文件 [" + file.name + "] 类型不正确！");
                            break;
                    }
                },
            });

            $("#updateUploadBtn").click(function() {
                $("#updateFoodPic").uploadify("upload", "*");
            });

        })();

    </script>
</body>

</html>
